const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');

// 计算文件的MD5值
const calculateMD5 = (file) => {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('md5');
    const stream = fs.createReadStream(file.path);
    stream.on('data', data => hash.update(data));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', error => reject(error));
  });
};

// 检查文件是否已存在
const checkFileExists = async (folder, md5) => {
  const uploadDir = path.join(__dirname, '../public/uploads', folder);
  if (!fs.existsSync(uploadDir)) {
    return null;
  }

  // 读取目录下的所有文件
  const files = fs.readdirSync(uploadDir);
  const md5MapPath = path.join(uploadDir, 'md5Map.json');
  
  // 读取或创建MD5映射文件
  let md5Map = {};
  if (fs.existsSync(md5MapPath)) {
    md5Map = JSON.parse(fs.readFileSync(md5MapPath, 'utf8'));
  }

  // 检查MD5是否存在
  if (md5Map[md5]) {
    return md5Map[md5];
  }

  return null;
};

// 保存MD5映射
const saveMD5Map = (folder, md5, filePath) => {
  const uploadDir = path.join(__dirname, '../public/uploads', folder);
  const md5MapPath = path.join(uploadDir, 'md5Map.json');
  
  let md5Map = {};
  if (fs.existsSync(md5MapPath)) {
    md5Map = JSON.parse(fs.readFileSync(md5MapPath, 'utf8'));
  }
  
  md5Map[md5] = filePath;
  fs.writeFileSync(md5MapPath, JSON.stringify(md5Map, null, 2));
};

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const folder = req.body.folder || 'default';
    const uploadDir = path.join(__dirname, '../public/uploads', folder);
    
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只能上传图片文件！'));
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

// 单个文件上传
router.post('/single', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      throw new Error('请选择要上传的文件');
    }

    const folder = req.body.folder || 'default';
    
    // 计算文件MD5
    const md5 = await calculateMD5(req.file);
    
    // 检查文件是否已存在
    const existingFile = await checkFileExists(folder, md5);
    if (existingFile) {
      // 如果文件已存在，删除刚上传的文件
      fs.unlinkSync(req.file.path);
      
      return res.status(200).json({
        success: true,
        data: {
          url: existingFile,
          md5: md5,
          isExisting: true
        }
      });
    }

    // 如果文件不存在，保存新文件的MD5映射
    const fileUrl = `/uploads/${folder}/${req.file.filename}`;
    saveMD5Map(folder, md5, fileUrl);
    
    res.status(200).json({
      success: true,
      data: {
        url: fileUrl,
        md5: md5,
        isExisting: false
      }
    });
  } catch (error) {
    // 发生错误时，删除已上传的文件
    if (req.file) {
      fs.unlinkSync(req.file.path);
    }
    
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

module.exports = router;